// 引入接口文件
import { getUserList,getProjectList,verifyCodeFun,editContent,getInfo} from './newsBulletinAddServ.js'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import {isEmpty, isArray, cloneDeep, merge} from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'

// 初始默认状态
const defultState = {
  btnLoading: false,
  loading: false,
  actionType: 'add',
  areaList: [],
  userList: [],
  products: [],
  areaShow: false,
  showUser: false,
  showProject: false,
  areaCheckAll: false,
  projectCheckAll: false,
  userCheckAll: false,
  temp: {
    areaIdList: [],
    userIdList: [],
    projectIdList: [],
  },
  query: {
    createTime: '',
    areaName: '',
    areaIds: '',
    projectName: '',
    projectIds: '',
    memberDatas: [],
    title: '',
    msg: '',
    creater: localStorage.getItem('username'),
  }
}

// 声明module
const tmpModule = {
  namespace: 'defaultModel',
  // 默认状态
  state: cloneDeep(defultState),
  // 入口函数(先执行)
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen(({ pathname, query }) => {
        // 页面路由匹配时执行
        if('' + tmpModule.pathname === '' + pathname){
          // 执行业务操作
          dispatch({ type: 'updateStore', payload: { ...cloneDeep(defultState), ...query } })//每次进去页面先重置状态
          dispatch({type: 'verifyCodeFun',payload: {query}})
        } // end if
      }) // end listen
    },
  },

  // 方法列表
  effects: {

    *verifyCodeFun({payload},{put,select,call}){
      if(yield call(verifyCodeFun,{})){
        if(payload.query.actionType == "check"){
          yield put({type: 'queryInfo',payload: payload}) // end dispatch
        }
        // 执行业务操作
        yield put({type: 'getProjectList', payload: {actionType: payload.query.actionType}})
      }
    },
    *queryInfo({payload}, {put, select, call}){
      let {query,userList,temp} = yield select(state => state[tmpModule.namespace])
      userList = []
      let params = { "id":payload.query.id }
      const { success, msg, msgData } = yield call(getInfo, params)
      if(success){
        query = {
          createTime: msgData.createTime,
          userName:msgData.userNames,
          title: msgData.title,
          msg: msgData.msg,
          creater: msgData.creater,
        }
        if(msgData.userNameList.length){
          for(var item of msgData.userNameList){
            let obj = {
              userId: item,
              userName: item
            }
            userList.push(obj)
          }
        }
        temp.areaIdList = msgData.areaIdList
        temp.projectIdList = msgData.projectIdList
        yield put({type: 'updateStore',payload: {query,userList}})
        yield put({type: 'getProjectList',payload: {}})
      }
    },
      //获取区域项目
      *getProjectList({payload},{put,select,call}){
        let {areaList} = yield select(state => state[tmpModule.namespace])
        let params = {
            level : 2,
          }
        const { data } = yield call(getProjectList, {...params})
          let list = data
          if(list.length){
            areaList =  list.map((item,index)=>{
              return {
                label: item.buname,
                value: item.buguid,
                children: item.childSysUninessunitList
              }
            })
            yield put({type: 'updateStore', payload: {areaList}})
          }
          yield put({type: 'filterProjectList', payload: {areaId:payload.areaId}})
      },
      *filterProjectList({payload},{put,select,call}){    
        let {products,areaList,temp,query,actionType} = yield select(state => state[tmpModule.namespace])
        let list = []
        let arr1 = []
        let arr2 = []
        for(var item of areaList){
          for(var itemed of temp.areaIdList){
            if(item.value == itemed){
              list.push(...item.children)
                if(actionType=='check'){
                  arr1.push(item.label)
                }
            }
          }
        }
        if(list.length){
          products =  list.map((item,index)=>{
            return {
              label: item.buname,
              value: item.buguid,
            }
          })
        }
        if(actionType=='check'){
          for(var it of products){
            for(var itt of temp.projectIdList){
              if(it.value == itt ){
                arr2.push(it.label)
              }
            }
          }
          query.areaName = arr1.join(',')
          query.projectName = arr2.join(',')
        }
        yield put({type: 'updateStore', payload: {products,query}})
      },
    //获取成员
    *getUserList({ payload }, { put, call, select }) {
      let {query,userList} = yield select(state => state[tmpModule.namespace])
      let params = {
        areaId: query.areaIds?query.areaIds:'',
        projectIds: query.projectIds?query.projectIds:''//#多个项目逗号分隔
      }
      const { rows,success } = yield call(getUserList, {...params})
      if(success){
        userList = rows
        yield put({type: 'updateStore', payload: {userList}})
      }
    },
    //保存，提交
    *editContent({ payload }, { put, call, select }) {
      let {btnLoading,query,userCheckAll} = yield select(state => state[tmpModule.namespace])
      query.memberDatas = JSON.stringify(query.memberDatas)
      if(userCheckAll){
      delete query.memberDatas
      }
      delete query.areaName
      delete query.projectName
      delete query.userName
      let params = query
      yield put({type: 'updateStore', payload: {btnLoading: true,}})
      const { rows,success } = yield call(editContent, {...params})
      if(success){
        message.success(msg)
        yield put({type: 'updateStore', payload: {btnLoading: false}})
        hashHistory.push({
          pathname: '/home/expandManage/newsBulletin',
          query: {}
        })
      }
    },
    
  },

  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
